package cn.com.darly.vpm.mobile;

import cn.com.darly.vpm.framework.common.StringDiyUtils;
import cn.com.darly.vpm.framework.common.UuidGenerateUtil;
import cn.com.darly.vpm.mobile.api.MobileLoginApi;
import cn.com.darly.vpm.mobile.cfg.EncryperAES;
import cn.com.darly.vpm.mobile.cfg.MobileBaseController;
import cn.com.darly.vpm.mobile.session.MobileSecurityData;
import cn.com.darly.vpm.mobile.session.MobileSecuritySchedule;
import cn.com.darly.vpm.mobile.session.SessionUtil;
import cn.com.darly.vpm.security.securitycfg.SecurityApi;
import cn.com.darly.vpm.security.user.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 * Author : ZhangYuHui
 * Date : 2017/10/18
 * TODO :
 */
@Controller
@RequestMapping("mobile")
public class MobileController extends MobileBaseController {
    @Autowired
    MobileLoginApi loginApi;
    @Autowired
    SecurityApi api;
    /**
     * @return 用户登录接口
     */
    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
    public void login(HttpServletRequest request, HttpServletResponse response) {
        String browser =findBrowser(request);
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            simpleResult("201", "编码出错",  request, response);
        }
        String account = request.getParameter("username");
        //此时密码为密文
        String pwd = request.getParameter("password");
        String deviceid = request.getParameter("deviceid");
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(pwd)||StringUtils.isEmpty(deviceid)) {
            super.simpleResult("201", "缺失登录参数", request, response);
            return;
        }
        String password = EncryperAES.Dncode(pwd);
        User user = loginApi.login(account);
        if (user == null) {
            saveLog(user.getId(),"0",0,3,user.getName(),browser,"[手机用户："+user.getName()+"登录失败]");

            super.simpleResult("201", "登录失败，没有此用户", request, response);
            return;
        }
        user.setDeviceId(deviceid);
        if (!loginApi.updateUser(user)){
            saveLog(user.getId(),"0",0,3,user.getName(),browser,"[手机用户："+user.getName()+"登录失败]");
            super.simpleResult("201", "登录失败，用户更新失败", request, response);
            return;
        }
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        if (!user.getPwd().equals(md5.encodePassword(password,user.getName()))) {
            saveLog(user.getId(),"0",0,3,user.getName(),browser,"[手机用户："+user.getName()+"登录失败]");
            super.simpleResult("201", "登录失败，账户密码错误", request, response);
            return;
        }
        saveLog(user.getId(),"0",0,3,user.getName(),browser,"[手机用户："+user.getName()+"登录成功]");
        List<String> str = api.getRoleListByUser(user.getId());
        user.setLoginDate(new Date());
        String key = SessionUtil.makeSessionKey(request);
        SessionUtil.SESSION_MAP.put(key, user);
        //记录用户最后操作时间
        SessionUtil.LAST_OPERATION_MAP.put(key, new Date());
        user.setToken(key);
        if (!str.isEmpty()) {
            user.setRoles(str.get(0));
        }
        dataResult("200", "登录成功。", user, request, response);
    }


    /**
     * @return 新用户注册接口
     */
    @RequestMapping(value = {"/register"}, method = RequestMethod.POST)
    public void register(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            simpleResult("201", "编码出错",  request, response);
        }

        String deviceid = request.getParameter("deviceid");
        if (StringDiyUtils.isEmpty(deviceid)){
            super.simpleResult("201", "设备信息错误", request, response);
            return;
        }
        String tel = request.getParameter("tel");
        if (StringUtils.isEmpty(tel)) {
            super.simpleResult("201", "手机号码为空", request, response);
            return;
        }
        User user = api.findUserByLoginName(tel);
        if (user!=null){
            super.simpleResult("201", "此号码已经注册，请使用找回密码或者更换号码重新注册", request, response);
            return;
        }
        String code =null;
        if (MobileSecuritySchedule.MOBILESECURITY.get(tel)==null) {
            code = (int) ((Math.random()*9+1)*100000)+"";
        }else {
            code = MobileSecuritySchedule.MOBILESECURITY.get(tel).getValue();
        }
        MobileSecurityData data = new MobileSecurityData();
        data.setKey(tel);
        data.setValue(code);
        data.setCreateDate(new Date());
        MobileSecuritySchedule.MOBILESECURITY.put(tel,data);
        dataResult("200", "验证成功", code, request, response);
        publishMessage("0#您的验证码为："+code+"，请凭借此验证码，验证手机号码",deviceid);
    }

    /**
     * @return 新用户注册接口
     */
    @RequestMapping(value = {"/registernext"}, method = RequestMethod.POST)
    public void registernext(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            simpleResult("201", "编码出错",  request, response);
        }
        String browser =findBrowser(request);
        String deviceid = request.getParameter("deviceid");
        if (StringDiyUtils.isEmpty(deviceid)){
            super.simpleResult("201", "设备信息为空", request, response);
            return;
        }
        String tel = request.getParameter("tel");
        if (StringUtils.isEmpty(tel)) {
            super.simpleResult("201", "手机号码为空", request, response);
            return;
        }
        String username = request.getParameter("username");
        if (StringUtils.isEmpty(username)) {
            super.simpleResult("201", "用户名为空", request, response);
            return;
        }
        String password = request.getParameter("password");
        if (StringUtils.isEmpty(password)) {
            super.simpleResult("201", "用户密码为空", request, response);
            return;
        }
        String pwd = EncryperAES.Dncode(password);
        User user = new User();
        user.setId(UuidGenerateUtil.getUUIDLong());
        user.setAccount(username);
        user.setName(username);
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        user.setPwd(md5.encodePassword(pwd,user.getName()));
        user.setMobile(tel);
        user.setDisabled(false);
        if (loginApi.registerUser(user)) {
            //当注册成功，录入数据库时，需要做如下操作：1.添加角色权限。2.添加日志记录
            //1.添加角色权限
            loginApi.setUserRole(user.getId(),browser);
            //2.添加日志记录
            saveLog(user.getId(),"0",0,3,user.getName(),browser,"[手机用户："+user.getName()+"注册成功]");
            dataResult("200", "恭喜您，注册成功", user, request, response);
        }else {
            simpleResult("201", "注册失败，服务端异常", request, response);
        }
    }

    /**
     * @return 验证用户名或者手机号已经注册
     */
    @RequestMapping(value = {"/checkuser"}, method = RequestMethod.POST)
    public void checkuser(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            simpleResult("201", "编码出错",  request, response);
        }
        String username = request.getParameter("username");
        if (StringUtils.isEmpty(username)) {
            super.simpleResult("201", "用户名为空", request, response);
            return;
        }
        if (api.findUserByLoginName(username)!=null) {
            super.simpleResult("201", "此账户已经注册，请更换", request, response);
        }else {
            super.simpleResult("200", "恭喜您，此账户无人使用", request, response);
        }
    }





}
